﻿using B.S.DataBase.MyProject.Domain.Sales;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure;
using ClosedXML.Excel;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using T.E.ERP.Write.API.Applicantions.Command.SaleOrderInfoCommand;
using T.E.ERP.Write.API.Applicantions.Command.SalesCommand;

namespace T.E.ERP.Write.API.Controllers
{
    /// <summary>
    /// 发货通知单-写
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SalesController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly SDbContext db;

        public SalesController(IMediator mediator,SDbContext db)
        {
            this.mediator = mediator;
            this.db = db;
        }
        /// <summary>
        /// 添加发货通知单并且物料信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public async Task<APIResult<int>> AddDelivey(AddDeliveryNoticeCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改发货通知单
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> UpdateDeliveys(UpdateDeliveryNoticeCommand request)
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 修改发货通知单状态
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> UpdateDeliveryState(UpdateSalesStateCommand request)
        {
            return await mediator.Send(request);
        }
        #region 退货通知单
        /// <summary>
        /// 添加退货通知单并且物料信息
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPost]
        public  async Task<APIResult<object>> Addreturn_notice_main(Addreturn_notice_mainCommand request)
        {
            return await mediator.Send(request);
        }


        /// <summary>
        /// 修改退货通知单
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<object>> Udpreturn_notice_main(Udpreturn_notice_mainCommand request)
        {
            return await mediator.Send(request);
        }

        /// <summary>
        /// 修改退货通知单审批状态
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> Udpreturn_notice_mainStatus(UdpreturnShenPiStatusCommand request)
        {
            return await mediator.Send(request);
        }



        /// <summary>
        /// 修改退货通知单(所有信息)
        /// </summary>
        /// <param name="request">请求</param>
        /// <returns>返回受影响的行数</returns>
        [HttpPut]
        public async Task<APIResult<int>> Udpreturn_notice_mainALL(UdpreturnmainCommand request)
        {
            return await mediator.Send(request);
        }



        #endregion

        /// <summary>
        /// 导入工作中心管理
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> ImportInventories(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>();
            try
            {
                // 检查上传文件是否为空
                if (file == null || file.Length <= 0)
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "未上传文件或文件为空";
                    return BadRequest(result);
                }

                // 检查文件扩展名是否为 Excel 格式
                var fileExtension = Path.GetExtension(file.FileName);
                if (fileExtension != ".xlsx" && fileExtension != ".xls")
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "仅支持上传 Excel 文件";
                    return BadRequest(result);
                }

                // 使用 MemoryStream 读取文件内容
                using (var stream = new MemoryStream())
                {
                    await file.CopyToAsync(stream);
                    using (var workbook = new XLWorkbook(stream))
                    {
                        // 导入 DeliveryNotice 表数据
                        var worksheet1 = workbook.Worksheet(1); // 获取第一个工作表
                        var rows1 = worksheet1.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<DeliveryNotice> job = new List<DeliveryNotice>();

                        foreach (var row in rows1)
                        {
                            var jobs = new DeliveryNotice();
                            jobs.NoticeId = row.Cell(1).GetValue<Guid>();
                            jobs.DocumentCode = row.Cell(2).GetValue<string>();
                            jobs.DocumentDate = row.Cell(3).GetValue<DateTime>();
                            jobs.BusinessTypeId = row.Cell(4).GetValue<int>();
                            jobs.WarehouseId = row.Cell(5).GetValue<int>();
                            jobs.Consignee = row.Cell(6).GetValue<string>();
                            jobs.Operator = row.Cell(7).GetValue<string>();
                            jobs.CustomerName = row.Cell(8).GetValue<string>();
                            jobs.Phone = row.Cell(9).GetValue<string>();
                            jobs.DocumentStatus = row.Cell(10).GetValue<string>();
                            jobs.Auditor = row.Cell(11).GetValue<string>();
                            jobs.AuditDate = row.Cell(12).GetValue<DateTime>();
                            jobs.BusinessStatusId = row.Cell(13).GetValue<int>();
                            jobs.FreightCost = row.Cell(14).GetValue<string>();
                            jobs.HandlingFee = row.Cell(15).GetValue<string>();
                            jobs.Address = row.Cell(16).GetValue<string>();
                            jobs.Remark = row.Cell(17).GetValue<string>();
                            jobs.IsDeleted = row.Cell(18).GetValue<bool>();
                            // 添加到要插入的列表中
                            job.Add(jobs);
                        }

                        var worksheet2 = workbook.Worksheet(1); // 获取第一个工作表
                        var rows2 = worksheet1.RowsUsed().Skip(1); // 跳过第一行（表头）

                        List<OrderMaterials> ordermaterialsList = new List<OrderMaterials>();

                        foreach (var row in rows2)
                        {
                            var ordermaterials = new OrderMaterials();
                            ordermaterials.SaleCode = row.Cell(1).GetValue<Guid>();
                            ordermaterials.MaterialsCode = row.Cell(2).GetValue<long>();
                            ordermaterials.MaterialsName = row.Cell(3).GetValue<string>();
                            ordermaterials.ModelSpecification = row.Cell(4).GetValue<string>();
                            ordermaterials.Calulate = row.Cell(5).GetValue<string>();
                            ordermaterials.CalulateNumber = row.Cell(6).GetValue<int>();
                            ordermaterials.OutBoundNumber = row.Cell(7).GetValue<int>();
                            ordermaterials.PackRequir = row.Cell(8).GetValue<string>();
                            // 添加到要插入的列表中
                            ordermaterialsList.Add(ordermaterials);
                        }
                        // 批量插入数据到数据库
                        await db.AddRangeAsync(job);
                        await db.AddRangeAsync(ordermaterialsList);
                        await db.SaveChangesAsync();

                        result.Code = APIEnum.添加成功;
                        result.Msg = "导入成功";
                        result.data = $"DeliveryNotice 表导入 {job.Count} 条记录，AnotherTable 表导入 {ordermaterialsList.Count} 条记录";
                    }
                }
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.添加失败;
                result.Msg = "导入失败，原因：" + ex.Message;
                return StatusCode(500, result);
            }
            return Ok(result);
        }

    }

}
